package com.lnj.messages.quarzJob;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.lnj.bean.dto.ProductDTO;
import com.lnj.bean.model.Product;
import com.lnj.messages.mapper.ProductMapper;
import com.lnj.messages.utiles.VectorUtil;
import co.elastic.clients.elasticsearch.core.search.Hit;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ESVectorJob implements Job {
    @Autowired
    private VectorUtil vectorUtil;

    @Autowired
    @Qualifier("taskExecutor")
    private Executor taskExecutor;
    @Autowired
    private ProductMapper productMapper;


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        try {
            // 构建搜索请求，获取所有商品
            List<ProductDTO> productDTOs = productMapper.findTodayUpdateProduct();

            // 例如：向量化处理、更新索引等
            processProducts(productDTOs);
            log.info("商品数据处理完成");

        } catch (Exception e) {
            log.error("处理商品数据时发生错误: " + e.getMessage());
            e.printStackTrace();
            throw new JobExecutionException("处理商品数据时发生错误", e);
        }

    }


    private void processProducts(List<ProductDTO> products) {
        // 示例：使用线程池异步处理每个商品
        for (ProductDTO product : products) {
            taskExecutor.execute(() -> {
                try {
                    // 对每个商品进行向量化处理
                    vectorUtil.storeVectorData(product);
                    log.info("商品 " + product.getProductId() + " 向量化处理完成");
                } catch (Exception e) {
                    log.error("处理商品 " + product.getProductId() + " 时发生错误: " + e.getMessage());
                    e.printStackTrace();
                }
            });
        }
    }
}
